<template>
  <div class="my-upload">
    <!--  -->
    <el-upload
      :accept="$imgSuffixArr"
      class="el-upload-wrap"
      :id="'el-upload' + count"
      :action="$upLoad"
      :class="fileList.length < limit ? '' : 'my'"
      :limit="limit"
      :show-file-list="true"
      :file-list="fileList"
      :ref="'el-upload' + count"
      list-type="picture-card"
      :auto-upload="autoUpload"
      :before-upload="beforeUpload"
      :multiple="multiple"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :on-progress="handleProcess"
      :disabled="disabled"
    >
      <!-- 裁剪的dom -->
      <template v-if="type == 'croper'">
        <template v-if="fileList.length == 0">
          <i v-if="!imgUrl" class="el-icon-plus avatar-uploader-icon"></i>
          <img :src="imgUrl" alt="" srcset="" :style="uploadStyle" />
        </template>
        <template v-else>
          <img :src="fileList[0].url" alt="" srcset="" />
        </template>
      </template>
      <!-- 普通上传的dom -->
      <template v-if="fileList.length < limit">
        <!-- <div slot="default" class="my-el-upload--picture-card"></div> -->
        <template v-if="type == 'only'">
          <img :src="imgUrl" alt="" srcset="" :style="uploadStyle" />
        </template>
        <template v-if="type == 'default'"
          ><i class="el-icon-plus avatar-uploader-icon" v-if="!imgUrl"></i
          ><img :src="imgUrl" alt="" srcset="" :style="uploadStyle"
        /></template>
      </template>
      <span slot="tip" style="color: #333"></span>

      <div slot="file" slot-scope="{ file }">
        <template v-if="file.fileType == 'image'">
          <img
            src="@/assets/upload/upload-image-close.png"
            v-if="showClose"
            alt=""
            class="img-ico-close"
            srcset=""
            @click="handleRemove(file, 'el-upload' + count)"
          />
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file, 'el-upload' + count)"
              v-if="operateType.includes('view')"
            >
              <i class="el-icon-zoom-in"></i>
            </span>
            <span
              v-if="!disabled && operateType.includes('down')"
              class="el-upload-list__item-delete"
              @click="handleDownload(file, 'el-upload' + count)"
            >
              <i class="el-icon-download"></i>
            </span>
            <span
              v-if="!disabled && operateType.includes('del')"
              class="el-upload-list__item-delete"
              @click="handleRemove(file, 'el-upload' + count)"
            >
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </template>
        <template v-if="file.fileType == 'video'">
          <video
            :ref="'video' + count"
            :id="'video' + count"
            :src="file.url"
            class="el-upload-list__item-thumbnail"
            style="height: 150px; width: 150px"
            controls="controls"
          >
            您的浏览器不支持视频播放
          </video>

          <span class="el-upload-list__item-actions">
            <span
              v-if="operateType.includes('view')"
              class="el-upload-list__item-preview"
              @click="handleVideoPreview(file, 'video' + count)"
            >
              <i class="el-icon-full-screen"></i>
            </span>
            <span
              v-if="!disabled && operateType.includes('del')"
              class="el-upload-list__item-delete"
              @click="handleRemove(file, 'el-upload' + count)"
            >
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </template>
        <el-progress
          v-if="file2Percentage[file.uid] && file2Percentage[file.uid] != 101"
          type="circle"
          :percentage="file2Percentage[file.uid]"
        ></el-progress>
      </div>
    </el-upload>
    <el-dialog title="图片" :visible.sync="dialogFormVisible">
      <div style="width: 100%; height: 500px">
        <vue-cropper
          autoCrop
          :fixedBox="option.fixedBox"
          :fixed="option.fixed"
          :fixedNumber="option.fixedNumber"
          :img="showImg"
          ref="cropper"
          centerBox
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import fileInfo from "../comp/const.js";
import croperMix from "../comp/croperMix.js";

const defaultOption = {
  limit: 9,
  maxSize: 20,
  multiple: true,
  operateType: ["view", "del", "down"],
};
var count = 10086;
export default {
  mixins: [croperMix],
  props: {
    fileList: {
      type: Array,
      default() {
        return [];
      },
    },
    limit: {
      type: Number,
      default: 2,
    },
    maxSize: {
      type: Number,
      default: 5, //5M
    },
    multiple: {
      type: Boolean,
      default: true, //一次上传多张
    },
    // 上传类型 default only croper
    type: {
      type: String,
      default: "default",
    },
    // 自定义默认上传样式
    uploadStyle: {
      type: Object,
      default() {
        return {};
      },
    },
    // 上传展示的默认图片
    imgUrl: {
      type: String,
      default: "",
    },
    showClose: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  created() {
    if (this.type == "default") {
      // 处理多张图
      // 操作类型
      this.operateType = ["view"];
    } else if (this.type == "only") {
      // 处理单张图 样式能定义
      this.operateType = ["view"];
    } else if (this.type == "croper") {
      // 处理单张图 自己单独上传
      this.autoUpload = false;
      this.operateType = ["view"];
      // this.showFileList = false;
    }
  },
  data() {
    return {
      operateType: [],
      autoUpload: true, //是否自动上传
      showFileList: true,
      //   fileUid2Type:{},
      //   tempFileList:[],

      //   dialogImageUrl: "",
      //   dialogVisible: false,
      tempFileList: [],
      count: ++count,

      file2Percentage: {},
      // disabled: false,
      //   fileList:[{
      //     fileType:'image',
      //     name:'123',
      //     url:'https://pic.bangbangtongcheng.com/63a682afa6af49b1b5e5a1944b0beff2'
      //   }]
    };
  },
  watch: {
    fileList: {
      handler(newV, oldV) {
        if (newV && newV.length > 0) {
          this.tempFileList = newV;

          // 直接赋值会导致this.fileList的url存的是本地blob,但显示效果是好的，所以增加一个字段mediaUrl作为上传的结果
          newV.map((i) => {
            if (!i.mediaUrl) {
              i.mediaUrl = i.response ? i.response.data[0].url : i.url;
            }
          });
        }
      },
      immediate: true,
    },
  },
  mounted() {
    setTimeout(() => {
      // console.log(this.$refs['el-upload10087'].$el.click());
      // this.$('.www button').click()
    }, 1000);
  },
  methods: {
    close() {
      this.dialogFormVisible = false;
      this.$emit("close");
    },

    openFileSelect() {
      document.querySelector(`#el-upload${this.count} .el-upload`).click();
      // this.$refs[`el-upload${this.count}`].$children[1].$el.click()
    },
    clearFileSelect() {
      this.$refs[`el-upload${this.count}`].clearFiles();
      while (this.fileList.pop()) {}
    },
    handleRemove(file, ref) {
      let uploadFiles = this.$refs[ref].uploadFiles;

      uploadFiles.splice(uploadFiles.indexOf(file), 1);
      this.fileList.splice(this.fileList.indexOf(file), 1);
    },
    handlePictureCardPreview(file, ref) {
      let uploadFiles = this.$refs[ref].uploadFiles;
      this.$hevueImgPreview({
        multiple: true,
        nowImgIndex: this.fileList.indexOf(file),
        imgList: this.fileList
          .filter((item) => item.fileType == "image")
          .map((item) => item.url),
      });
    },
    handleVideoPreview(file, ref) {
      this.Screen(this.$refs[ref]);
    },
    Screen(element) {
      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
      } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
      } else if (element.oRequestFullscreen) {
        element.oRequestFullscreen();
      } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullScreen();
      } else {
        var docHtml = document.documentElement;
        var docBody = document.body;
        var videobox = document.getElementById("video");
        var cssText = "width:100%;height:100%;overflow:hidden;";
        docHtml.style.cssText = cssText;
        docBody.style.cssText = cssText;
        element.style.cssText = cssText + ";" + "margin:0px;padding:0px;";
        document.IsFullScreen = true;
      }
    },
    handleDownload(file) {
      console.log(file);
      //   return;
      fetch(file.response.data[0].url).then((res) => {
        console.log(res);
        res.blob().then((blob) => {
          const blobUrl = window.URL.createObjectURL(blob);
          // 这里的文件名根据实际情况从响应头或者url里获取
          // const filename = fileName;
          const a = document.createElement("a");
          a.href = blobUrl;
          // a.download = filename;
          a.click();
          window.URL.revokeObjectURL(blobUrl);
        });
      });
    },
    beforeUpload(file) {
      console.log("beforeUpload", file);
      console.log("beforeUpload", fileInfo.fileType(file.type));

      // 限制文件大小
      if (this.maxSize && file.size / (1024 * 1024) > this.maxSize) {
        this.$message.warning(`当前限制文件大小不能大于${this.maxSize}M`);
        return false;
      }
      // 传输类型
      if (this.accept) {
        //不赋值就不做限制
        if (!this.accept.split(",").includes(fileInfo.fileType(file.type))) {
          this.$message({
            message: "文件格式错误",
            type: "error",
            duration: 2000,
          });
          return false;
        }
      }
      //   console.log(file);
      return true;
    },
    reDefineProperties(obj) {
      Object.defineProperties(obj, {
        type: {
          //定义属性x
          // value :'1',
          writable: true, //可写
        },
        // type : {  //定义属性y
        //     set : function (x) {  //设置访问器属性
        //         this.x = x;  //改写obj对象的x属性的值
        //     },
        //     get : function () {  //设置访问器
        //         return this.x;
        //     },
        // }
      });
    },
    handleExceed(files, fileList) {
      console.log("handleExceed=>当前选择的多或者单文件", files);
      console.log("handleExceed=>已经存在的文件列表", fileList);

      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${this.fileList.length + files.length} 个文件`
      );
    },
    handleSuccess(response, file, fileList) {
      // console.log("handleSuccess", response);
      console.log("handleSuccess", file);
      file.fileType = fileInfo.fileType(file);
      // this.tempFileList.push({
      //     name:file.name,
      //     url: response.data[0].url,
      //     fileType:fileInfo.fileType(file)
      // });
      // console.log("handleSuccess", fileList);
      // fileList.map((item)=>{
      //     if(item.response){
      //         this.fileList.push({
      //             name:file.name,
      //             url: response.data[0].url,
      //             fileType:fileInfo.fileType(file)
      //         });
      //     }
      // })
    },

    handleChange(file, fileList) {
      console.log("handleChangehandleChangehandleChange", fileList);
      console.log("handleChangehandleChangehandleChange", this.fileList);
      // 如果是裁剪
      if (this.type == "croper") {
        this.prepare(file);
        return false;
      }

      if (file.percentage == 100) {
        this.file2Percentage[file.uid] = 101;
        setTimeout(() => {
          // this.handleArr(fileList);
          // console.log(
          //   "objectobjectobjectobject",
          //   JSON.stringify(fileList, null, 2)

          // );
          console.log(this.fileList);
        }, 1500);

        // return;

        // this.fileList = fileList
      }
      // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
      if (file.percentage == 0) {
        // this.fileUid2Type[file.uid]= fileInfo.fileType(file)
        // console.log(this.fileUid2Type);

        this.file2Percentage = {
          ...this.file2Percentage,
          [file.uid]: 0,
        };
        console.log(this.file2Percentage);
      }
      // console.log('handleChange',file);
      // 没有拦截作用
    },
    handleArr(arr) {
      var that = this;
      arr.map((i, j) => {
        // 如果检测不存在id。。。但好像没什么必要，可以直接 this.fileList = fileList

        if (!i.mediaUrl) {
          // console.log("arr.map", i.response.data[0].url);
          // return;
          i.mediaUrl = i.response ? i.response.data[0].url : "";
        }
        // console.log("arr.map", i.response.data[0].url);
        // i.mediaUrl = i.response ? i.response.data[0].url : "";

        if (getId(i.uid)) {
          //可以操作
          this.fileList.push(i);
        }
      });
      console.log("handleArr=>", this.fileList);
      function getId(uid) {
        var flag = true;
        that.fileList.map((item) => {
          if (flag && item.uid == uid) {
            flag = false;
          }
        });
        return flag;
      }
    },
    handleProcess(event, file, fileList) {
      let _self = this;
      if (event.lengthComputable) {
        let val = ((event.loaded / event.total) * 100).toFixed(0);
        var progress = parseInt(val);
        _self.file2Percentage[file.uid] = progress;
        // console.log(_self.file2Percentage[file.uid]);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
// 删除图标
.img-ico-close {
  z-index: 99;
  position: absolute;
  top: -11px;
  right: -11px;
  width: 22px;
  height: 22px;
}
.my-upload {
  display: inline-block;
  text-align: center;
  cursor: pointer;
  outline: 0;
  width: 100%;
  height: 100%;

  .el-upload-wrap {
    width: 100%;
    height: 100%;
  }
  // 让上传的图片铺满框
  .el-upload-list__item {
    & > div {
      width: 100%;
      height: 100%;
      img {
        object-fit: fill;
      }
    }
  }
  // 自定义默认图片需要它
  ::v-deep .el-upload {
    position: relative;
  }
  // 想改变什么但没起到效果
  ::v-deep .my-el-upload--picture-card {
    // background-color: #fbfdff;
    // border: 1px dashed #c0ccda;
    // border-radius: 6px;
    // box-sizing: border-box;
    // width: 148px;
    // height: 148px;
    // cursor: pointer;
    // line-height: 146px;
    // vertical-align: top;
  }
  ::v-deep .my-el-upload {
    display: inline-block;
    text-align: center;
    cursor: pointer;
    outline: 0;
  }
  // 如果数量达到限制就让上传框none
  .my {
    ::v-deep .el-upload {
      display: none;
    }
  }
  // 默认样式影响了这个，只能再次覆盖
  ::v-deep .el-upload__input {
    display: none !important;
  }
}
</style>
